#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/18 14:33
    Desc  :
--------------------------------------
"""
from django.core.paginator import Paginator
from django.db import transaction
from django.urls import path
from django.utils.decorators import method_decorator
from django_http_log.common.request import BaseAPIView
from django_http_log.common.response import SystemExceptionResponse, CommonResponse, SuccessResponse

from common.decorator.token_decorator import isAuthentication
from common.enums.response_enums import CommonResultEnums
from common.utils.log_utils import logger
from common.utils.other_utils import get_time
from common.utils.token_utils import RequestAuthTokenUtil
from person.models import Role
from person.serializers.role import RoleSerializer, RoleListSerializer
from platform_auth.settings import APIDOC_DECORATOR


class RoleBaseAPIView(BaseAPIView):
    Model = Role

    serializer_class = RoleSerializer

    search_fields = ['name']


class RoleAddAPIView(RoleBaseAPIView):
    """
    角色新增
    """

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'role', desc = '角色管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/role/add', summary = '角色新增')
    @APIDOC_DECORATOR.ApiParams(value = 'name', require = True, type = 'string', desc = '角色名称')
    @APIDOC_DECORATOR.ApiParams(value = 'remark', type = 'string', desc = '备注')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()

            name = body.get('name')

            queryset = self.Model.objects.filter(name = name, deleted = False)
            # 判断角色名称是否存在
            if queryset.count() != 0:
                return CommonResponse(codeEnums = CommonResultEnums.ROLE_NAME_IS_EXIST)

            with transaction.atomic():

                role = self.Model.objects.create(
                    name = name,
                    persons = '',
                    menus = '',
                    creatorId = userId,
                    creatorName = userName,
                )
            serializer = self.serializer_class(role, exclude = self.exclude_fields)

            return SuccessResponse(result = serializer.data)

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class RoleListAPIView(RoleBaseAPIView):
    """
    角色新增
    """
    serializer_class = RoleListSerializer

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'role', desc = '角色管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/role/list', summary = '角色列表')
    @APIDOC_DECORATOR.ApiParams(value = 'pageIndex', type = 'int', require = True, desc = '页码')
    @APIDOC_DECORATOR.ApiParams(value = 'pageSize', type = 'int', require = True, desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'name', type = 'string', desc = '角色名称', remark = '模糊查询')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            pageIndex, pageSize = request.data.get('pageIndex'), request.data.get('pageSize')
            if len(self.search_fields) != 0:
                queryset = self.Model.objects.filter(**self.search_queryset(request), deleted = False)
            else:
                queryset = self.Model.objects.filter(deleted = False)

            serializer = self.serializer_class(queryset, many = True)
            pageData = Paginator(serializer.data, pageSize)
            data = {
                'pageCount': pageData.count,
                'pageIndex': pageIndex,
                'pageSize': pageSize,
                'list': pageData.page(pageIndex).object_list
            }

            return SuccessResponse(result = data)
        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class RoleEditAPIView(RoleBaseAPIView):
    """
    角色新增
    """

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'role', desc = '角色管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/role/edit', summary = '角色编辑')
    @APIDOC_DECORATOR.ApiParams(value = 'roleId', type = 'int', require = True, desc = '角色Id')
    @APIDOC_DECORATOR.ApiParams(value = 'name', type = 'string', desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'remark', type = 'string', desc = '备注')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()

            name = body.get('name')

            roleId = body.get('roleId')

            queryset_role_id = self.Model.objects.filter(id = roleId, deleted = False)

            if queryset_role_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.ROLE_ID_IS_NOT_EXIST)

            with transaction.atomic():
                data = queryset_role_id.update(
                    name = name,
                    remark = body.get('remark'),
                    updaterName = userName,
                    updaterId = userId,
                    updateTime = get_time(),
                )
            serializer = self.serializer_class(data, exclude = self.exclude_fields)

            return SuccessResponse(result = serializer.data)

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class RoleDeleteAPIView(RoleBaseAPIView):
    """
    角色新增
    """

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'role', desc = '角色管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/role/delete', summary = '角色删除')
    @APIDOC_DECORATOR.ApiParams(value = 'roleId', type = 'int', require = True, desc = '角色Id')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()

            roleId = body.get('roleId')

            queryset_role_id = self.Model.objects.filter(id = roleId, deleted = False)

            if queryset_role_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.ROLE_ID_IS_NOT_EXIST)

            with transaction.atomic():
                queryset_role_id.update(
                    deleted = True,
                    deleteTime = get_time(),
                    updaterName = userName,
                    updaterId = userId,
                    updateTime = get_time(),
                )

            return SuccessResponse()

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


urlpatterns = [
    path('add', RoleAddAPIView.as_view()),
    path('list', RoleListAPIView.as_view()),
    path('edit', RoleEditAPIView.as_view()),
    path('delete', RoleDeleteAPIView.as_view()),
]
